redis 模糊查找keys
Redis入门教程可参考:超强、超详细Redis数据库入门教程
Redis操作命令可参考:Redis操作命令总结
redis可以通过命令Keys Match来进行键值的模糊匹配,借助StackExchange.Redis时,由于Dll内部没有实现Keys Match的操作,不过,StackExchange.Redis提供了直接执行Lua语句的入口:
RedisResult ScriptEvaluate(LoadedLuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None); RedisResult ScriptEvaluate(string script, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None); RedisResult ScriptEvaluate(byte[] hash, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None); RedisResult ScriptEvaluate(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None);
Windows下调试Lua的环境搭建可参考如下:Windows下Lua+Redis 断点调试环境搭建==Linux下类似
Keys Match,当数据规模较大时使用,会严重影响Redis性能,Redis还可以通过SCAN命令模糊匹配Key。
以上两种方式的Lua语句如下:
//使用Keys *模糊匹配Key return redis.call('keys',KEYS[1]) //使用SCAN模糊匹配Key local dbsize=redis.call('dbsize') local res=redis.call('scan',0,'match',KEYS[1],'count',dbsize) return res[2]
StackExchange.Redis调用如下:
private static object _locker = new Object(); private static ConnectionMultiplexer _instance = null; public static ConnectionMultiplexer Instance { get { if (_instance == null) { lock (_locker) { if (_instance == null || !_instance.IsConnected) { _instance = ConnectionMultiplexer.Connect(ConfigUtils.ArrangeResultHost); } } } return _instance; } } public static IDatabase GetDatabase() { return Instance.GetDatabase(); } //使用Keys *模糊匹配Key public static List<string> GetKeys(string key) { var result=(string[])GetDatabase().ScriptEvaluate(LuaScript.Prepare("return redis.call('KEYS',@keypattern)"),new{ keypattern=key }); return result.ToList(); } //使用SCAN模糊匹配Key public static List<string> GetKeys(string key) { var result = (string[])GetDatabase().ScriptEvaluate( LuaScript.Prepare("local dbsize=redis.call('dbsize') local res=redis.call('scan',0,'match',KEYS[1],'count',dbsize) return res[2]"), new RedisKey[] { key }); return result.ToList(); }